package com.yusheng.tr.common.core.config;

import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.TypeFactory;
import com.yusheng.domain.R;
import com.yusheng.exceptions.ServiceException;
import feign.Response;
import feign.codec.Decoder;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.io.Reader;
import java.lang.reflect.Type;
import java.nio.charset.Charset;

// 注入 Jackson 的 ObjectMapper，如果不喜欢 Lombok 可以自行修改
@RequiredArgsConstructor
@Slf4j
public class UnwrapDecoder implements Decoder {
    private final ObjectMapper objectMapper;

    @SneakyThrows
    @Override
    public Object decode(Response response, Type type) {
        log.info("*****{}","start jie xi");
        Reader reader = response.body().asReader(Charset.defaultCharset());
        R<?> result = objectMapper.readValue(reader, R.class);
        // 根据 code 判断操作是否成功
        if (result.getCode() == 200) {
            Object data = result.getData();
            JavaType javaType = TypeFactory.defaultInstance().constructType(type);
            return objectMapper.convertValue(data, javaType);
        }
        // 若不成功，抛出业务异常，注意此处的异常会在 DecodeException 中被捕获，后文会处理
        throw new ServiceException(result.getMessage(),result.getCode());
    }
}

